<template>
  <div class="industry-analysis-container">
    <!-- 顶部导航 -->
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/graph-analysis' }">知识图谱分析</el-breadcrumb-item>
        <el-breadcrumb-item>行业企业综合分析</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button type="text" @click="backToMain">
        <el-icon><Back /></el-icon> 返回知识图谱分析
      </el-button>
    </div>

    <!-- API环境检测状态提示 -->
    <el-alert
      v-if="!dataReady"
      title="正在初始化分析环境，请稍候..."
      type="info"
      :closable="false"
      show-icon
      class="api-status-alert"
    />

    <!-- 顶部标签页切换 -->
    <el-tabs v-model="activeTab" class="analysis-tabs" @tab-click="handleTabClick">
      <el-tab-pane name="industry" label="行业分析">
        <template #label>
          <div class="tab-label">
            <el-icon><TrendCharts /></el-icon> 行业分析
          </div>
        </template>
      </el-tab-pane>
      
      <el-tab-pane name="region" label="区域分布分析">
        <template #label>
          <div class="tab-label">
            <el-icon><MapLocation /></el-icon> 区域分布分析
          </div>
        </template>
      </el-tab-pane>
    </el-tabs>

    <!-- 分析内容区域 -->
    <div class="analysis-layout">
      <!-- 左侧查询表单 -->
      <el-card class="form-card" shadow="hover">
        <!-- 行业分析表单 -->
        <template v-if="activeTab === 'industry'">
          <industry-analysis-form 
            :loading="loading" 
            @query="handleIndustryQuery"
          />
        </template>
        
        <!-- 区域分析表单 -->
        <template v-else-if="activeTab === 'region'">
          <region-analysis-form 
            :loading="loading" 
            @query="handleRegionQuery"
          />
        </template>
      </el-card>

      <!-- 右侧分析结果 -->
      <el-card class="result-card" shadow="hover" v-loading="loading">
        <!-- 行业分析结果 -->
        <template v-if="activeTab === 'industry' && industryData">
          <div class="industry-stats">
            <!-- 顶部卡片指标 -->
            <el-row :gutter="20" class="stat-cards">
              <el-col :span="8" v-for="(stat, index) in industryStats" :key="index">
                <el-card class="stat-card" :body-style="{ padding: '15px' }">
                  <div class="stat-content">
                    <div class="stat-icon">
                      <el-icon :size="30" :color="stat.color">
                        <component :is="stat.icon" />
                      </el-icon>
                    </div>
                    <div class="stat-info">
                      <div class="stat-value">{{ formatValue(stat.value) }}</div>
                      <div class="stat-label">{{ stat.label }}</div>
                    </div>
                  </div>
                  <div class="stat-trend" v-if="stat.trend">
                    <el-tag 
                      :type="stat.trend.type === 'up' ? 'success' : stat.trend.type === 'down' ? 'danger' : 'info'"
                      size="small"
                    >
                      {{ stat.trend.value }}{{ stat.trend.unit }}
                    </el-tag>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <!-- 企业规模和类型分布图表 -->
            <el-row :gutter="20" class="chart-row">
              <el-col :span="12">
                <el-card class="chart-card">
                  <template #header>
                    <div class="chart-header">
                      <span>企业规模分布</span>
                      <el-tooltip content="企业规模分布情况" placement="top">
                        <el-icon><InfoFilled /></el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <div class="chart-container" ref="companySizeChart"></div>
                </el-card>
              </el-col>

              <el-col :span="12">
                <el-card class="chart-card">
                  <template #header>
                    <div class="chart-header">
                      <span>企业类型分布</span>
                      <el-tooltip content="企业类型分布情况" placement="top">
                        <el-icon><InfoFilled /></el-icon>
                      </el-tooltip>
                    </div>
                  </template>
                  <div class="chart-container" ref="companyTypeChart"></div>
                </el-card>
              </el-col>
            </el-row>

            <!-- 专利分布和创新能力排行 -->
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>专利分布Top10</span>
                  <el-tooltip content="拥有专利数量最多的十家企业" placement="top">
                    <el-icon><InfoFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <div class="chart-container" ref="patentRankChart"></div>
            </el-card>
            
            <!-- 创新效率排行图表 -->
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>创新效率Top10</span>
                  <el-tooltip content="按专利数/员工数计算的创新效率排名" placement="top">
                    <el-icon><InfoFilled /></el-icon>
                  </el-tooltip>
                </div>
              </template>
              <div class="chart-container" ref="innovationChart"></div>
            </el-card>
          </div>
        </template>

        <!-- 区域分析结果 -->
        <template v-else-if="activeTab === 'region'">
          <div class="region-stats">
            <!-- 有数据时显示区域企业统计图表 -->
            <template v-if="regionData && regionData.length > 0">
              <div class="region-stats-title">
                <h3>区域企业统计图表</h3>
                <p class="region-stats-desc">区域企业统计功能可以帮您了解各省份企业的分布情况、员工数量、注册资本和高新技术企业数量等关键指标</p>
                <p class="region-stats-hint">点击查询按钮获取最新的区域企业统计数据，系统将为您生成四个维度的统计图表。</p>
              </div>
              <div class="quadrant-layout">
                <el-card shadow="hover" class="quadrant-card">
                  <template #header>
                    <div class="chart-header">
                      <span>各省企业数量统计</span>
                    </div>
                  </template>
                  <div class="chart-container" ref="companyCountChart"></div>
                </el-card>
                
                <el-card shadow="hover" class="quadrant-card">
                  <template #header>
                    <div class="chart-header">
                      <span>各省员工数量统计</span>
                    </div>
                  </template>
                  <div class="chart-container" ref="employeeCountChart"></div>
                </el-card>
                
                <el-card shadow="hover" class="quadrant-card">
                  <template #header>
                    <div class="chart-header">
                      <span>各省注册资本统计</span>
                    </div>
                  </template>
                  <div class="chart-container" ref="registeredCapitalChart"></div>
                </el-card>
                
                <el-card shadow="hover" class="quadrant-card">
                  <template #header>
                    <div class="chart-header">
                      <span>各省高新企业数量统计</span>
                    </div>
                  </template>
                  <div class="chart-container" ref="highTechCountChart"></div>
                </el-card>
              </div>
            </template>
            
            <!-- 无数据时显示空状态 -->
            <template v-else>
              <el-empty :description="emptyDescription">
                <template #description>
                  <p>{{ emptyDescription }}</p>
                  <p v-if="!dataReady" class="empty-tip">系统正在初始化分析环境，请稍候再试...</p>
                </template>
              </el-empty>
            </template>
          </div>
        </template>

        <!-- 空状态 -->
        <template v-else>
          <el-empty :description="emptyDescription">
            <template #description>
              <p>{{ emptyDescription }}</p>
              <p v-if="!dataReady" class="empty-tip">系统正在初始化分析环境，请稍候再试...</p>
            </template>
          </el-empty>
        </template>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { 
  TrendCharts, 
  MapLocation, 
  OfficeBuilding, 
  DataAnalysis, 
  Money,
  InfoFilled,
  Back
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts/core';
import {
  TooltipComponent,
  LegendComponent,
  GridComponent,
  TitleComponent
} from 'echarts/components';
import { PieChart, BarChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import { getIndustryComprehensiveAnalysis, getCompanyStats } from '@/api/graphAnalysis';

// 导入自定义组件
import IndustryAnalysisForm from '@/components/graph-analysis/IndustryAnalysisForm.vue';
import RegionAnalysisForm from '@/components/graph-analysis/RegionAnalysisForm.vue';
import RegionMapChart from '@/components/graph-analysis/RegionMapChart.vue';

// 注册 ECharts 组件
echarts.use([
  TooltipComponent,
  LegendComponent,
  GridComponent,
  TitleComponent,
  PieChart,
  BarChart,
  CanvasRenderer
]);

// 防抖函数
function debounce(fn, delay = 100) {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

export default {
  name: 'IndustryAnalysis',
  components: {
    IndustryAnalysisForm,
    RegionAnalysisForm,
    RegionMapChart,
    TrendCharts, 
    MapLocation, 
    OfficeBuilding, 
    DataAnalysis, 
    Money,
    InfoFilled,
    Back
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const query = route.query;
    
    // 状态变量
    const activeTab = ref('industry');
    const loading = ref(false);
    const industryData = ref(null);
    const regionData = ref(null);
    // industryStats改为computed属性，下面会定义
    const activeDimension = ref('companyCount');
    const dataReady = ref(false);

    // 添加环境检测参数
    const isFromMainPage = computed(() => query.from === 'graph-analysis');
    
    // 图表实例收集，用于统一管理销毁
    const chartInstances = [];
    
    const addChartInstance = (instance) => {
      if (instance && !chartInstances.includes(instance)) {
        chartInstances.push(instance);
      }
    };
    
    // 安全地初始化图表，避免多次创建同一个DOM上的图表
    const safeInitChart = (dom) => {
      if (!dom) return null;
      
      try {
        // 使用ECharts初始化图表，添加性能优化选项
        const chart = echarts.init(dom, null, {
          renderer: 'canvas', 
          useDirtyRect: true
        });
        
        // 添加到实例列表以便统一管理
        addChartInstance(chart);
        return chart;
      } catch (error) {
        console.error('图表初始化失败:', error);
        return null;
      }
    };
    
    // 检测API环境
    const checkApiEnvironment = async () => {
      // 此函数用于检测API环境并调整数据处理方式
      try {
        const testParams = {
          industryName: '计算机、通信和其他电子设备制造业',
          analysisType: 'industry'
        };
        
        const response = await getCompanyStats(testParams);
        
        if (response) {
          console.log('API环境检测成功:', response);
          dataReady.value = true;
        }
      } catch (error) {
        console.error('API环境检测失败:', error);
        // 不阻止用户继续使用，只是记录错误
      }
    };
    
    // 查询参数预处理
    const processQueryParams = () => {
      try {
        // 如果URL中带有查询参数，尝试直接执行查询
        if (route.query.industryName) {
          const params = {
            industryName: route.query.industryName,
            industryId: route.query.industryId
          };
          
          if (route.query.analysisType === 'region') {
            activeTab.value = 'region';
            handleRegionQuery({
              ...params,
              province: route.query.province || '',
              dimension: route.query.dimension || 'companyCount'
            });
          } else {
            activeTab.value = 'industry';
            handleIndustryQuery(params);
          }
        }
      } catch (error) {
        console.error('处理查询参数失败:', error);
      }
    };
    
    // 图表实例引用
    const companySizeChart = ref(null);
    const companyTypeChart = ref(null);
    const patentRankChart = ref(null);
    const regionRankChart = ref(null);
    const innovationChart = ref(null);
    
    // 图表实例
    let companySizeChartInstance = null;
    let companyTypeChartInstance = null;
    let patentRankChartInstance = null;
    let regionRankChartInstance = null;
    let innovationChartInstance = null;

    // 计算属性
    const industryStats = computed(() => {
      if (!industryData.value) return [];
      
      const data = industryData.value;
      console.log('计算行业统计指标，原始数据:', data);
      
      // 尝试从industryStatistics获取关键数据
      let totalCompanies = 0;
      let highTechCompanies = 0;
      let avgRegisteredCapital = 0;
      let highTechRatio = 0;
      
      if (data.industryStatistics) {
        // 直接从industryStatistics获取数据
        const stats = data.industryStatistics;
        
        totalCompanies = typeof stats.companyCount === 'number' ? stats.companyCount : 0;
        highTechCompanies = typeof stats.hightechCount === 'number' ? stats.hightechCount : 0;
        avgRegisteredCapital = typeof stats.avgCapital === 'number' ? stats.avgCapital : 0;
        highTechRatio = typeof stats.hightechRatio === 'number' ? stats.hightechRatio : 0;
      } else {
        // 如果没有找到industryStatistics，尝试从其他位置获取
        // 尝试获取总企业数
        if (typeof data.totalCompanies === 'number') {
          totalCompanies = data.totalCompanies;
        } else if (data.data && typeof data.data.totalCompanies === 'number') {
          totalCompanies = data.data.totalCompanies;
        } else if (data.result && typeof data.result.totalCompanies === 'number') {
          totalCompanies = data.result.totalCompanies;
        } else {
          // 尝试查找其他可能的字段
          const possibleTotalKeys = ['totalCount', 'total', 'count', 'enterprises', 'companyCount'];
          for (const key of possibleTotalKeys) {
            if (typeof data[key] === 'number') {
              totalCompanies = data[key];
              break;
            } else if (data.data && typeof data.data[key] === 'number') {
              totalCompanies = data.data[key];
              break;
            } else if (data.result && typeof data.result[key] === 'number') {
              totalCompanies = data.result[key];
              break;
            }
          }
        }
        
        // 尝试获取高新技术企业数
        if (typeof data.highTechCompanies === 'number') {
          highTechCompanies = data.highTechCompanies;
        } else if (data.data && typeof data.data.highTechCompanies === 'number') {
          highTechCompanies = data.data.highTechCompanies;
        } else if (data.result && typeof data.result.highTechCompanies === 'number') {
          highTechCompanies = data.result.highTechCompanies;
        } else {
          // 尝试查找其他可能的字段
          const possibleHighTechKeys = ['highTechCount', 'highTech', 'highTechNumber', 'hightechCount'];
          for (const key of possibleHighTechKeys) {
            if (typeof data[key] === 'number') {
              highTechCompanies = data[key];
              break;
            } else if (data.data && typeof data.data[key] === 'number') {
              highTechCompanies = data.data[key];
              break;
            } else if (data.result && typeof data.result[key] === 'number') {
              highTechCompanies = data.result[key];
              break;
            }
          }
        }
        
        // 尝试获取平均注册资本
        if (typeof data.avgRegisteredCapital === 'number') {
          avgRegisteredCapital = data.avgRegisteredCapital;
        } else if (data.data && typeof data.data.avgRegisteredCapital === 'number') {
          avgRegisteredCapital = data.data.avgRegisteredCapital;
        } else if (data.result && typeof data.result.avgRegisteredCapital === 'number') {
          avgRegisteredCapital = data.result.avgRegisteredCapital;
        } else {
          // 尝试查找其他可能的字段
          const possibleCapitalKeys = ['avgCapital', 'averageCapital', 'avgRegCapital', 'capitalAvg'];
          for (const key of possibleCapitalKeys) {
            if (typeof data[key] === 'number') {
              avgRegisteredCapital = data[key];
              break;
            } else if (data.data && typeof data.data[key] === 'number') {
              avgRegisteredCapital = data.data[key];
              break;
            } else if (data.result && typeof data.result[key] === 'number') {
              avgRegisteredCapital = data.result[key];
              break;
            }
          }
        }
        
        // 计算高新技术企业比例
        if (typeof data.highTechRatio === 'number') {
          highTechRatio = data.highTechRatio;
        } else if (data.data && typeof data.data.highTechRatio === 'number') {
          highTechRatio = data.data.highTechRatio;
        } else if (data.result && typeof data.result.highTechRatio === 'number') {
          highTechRatio = data.result.highTechRatio;
        } else if (totalCompanies > 0) {
          highTechRatio = highTechCompanies / totalCompanies;
        }
      }
      
      console.log('计算出的行业统计指标:', {
        totalCompanies,
        highTechCompanies,
        avgRegisteredCapital,
        highTechRatio
      });
      
      return [
        {
          label: '企业总数',
          value: totalCompanies,
          icon: 'OfficeBuilding',
          color: '#409EFF'
        },
        {
          label: '高新技术企业',
          value: highTechCompanies,
          icon: 'DataAnalysis',
          color: '#67C23A',
          trend: {
            type: 'up',
            value: highTechRatio ? (highTechRatio * 100).toFixed(1) : 0,
            unit: '%'
          }
        },
        {
          label: '平均注册资本',
          value: avgRegisteredCapital,
          icon: 'Money',
          color: '#E6A23C',
          unit: '万元'
        }
      ];
    });

    const getDimensionTitle = computed(() => {
      const titles = {
        companyCount: '企业数量区域分布',
        employeeCount: '员工数量区域分布',
        registeredCapital: '注册资本区域分布',
        highTechCount: '高新企业区域分布'
      };
      return titles[activeDimension.value] || '企业数量区域分布';
    });

    const emptyDescription = computed(() => {
      return activeTab.value === 'industry' 
        ? '请选择行业开始分析' 
        : '请选择行业和分析维度开始区域分析';
    });

    // 方法
    const handleTabClick = () => {
      // 切换标签页时清空数据
      if (activeTab.value === 'industry') {
        regionData.value = null;
      } else {
        industryData.value = null;
      }
    };

    const backToMain = () => {
      // 返回到知识图谱分析页面，并通过查询参数设置活动标签页
      router.push({
        path: '/graph-analysis',
        query: { tab: 'industryComprehensive' }
      });
    };

    // 添加数据修复函数，确保数据格式正确
    const fixIndustryData = (data) => {
      if (!data) return null;
      
      const result = { ...data };
      
      // 确保基本统计数据存在
      if (!result.totalCompanies && result.totalCompanies !== 0) {
        result.totalCompanies = 0;
      }
      
      if (!result.highTechCompanies && result.highTechCompanies !== 0) {
        result.highTechCompanies = 0;
      }
      
      if (!result.avgRegisteredCapital && result.avgRegisteredCapital !== 0) {
        result.avgRegisteredCapital = 0;
      }
      
      // 确保高新技术比例数据存在
      if (!result.highTechRatio && result.highTechRatio !== 0) {
        if (result.totalCompanies > 0) {
          result.highTechRatio = result.highTechCompanies / result.totalCompanies;
        } else {
          result.highTechRatio = 0;
        }
      }
      
      // 确保企业规模分布数据存在
      if (!result.companySizeDistribution) {
        result.companySizeDistribution = {
          '大型企业': 0,
          '中型企业': 0,
          '小型企业': 0,
          '微型企业': 0
        };
      }
      
      // 确保企业类型分布数据存在
      if (!result.companyTypeDistribution) {
        result.companyTypeDistribution = {
          '有限责任公司': 0,
          '股份有限公司': 0,
          '个体工商户': 0,
          '其他类型': 0
        };
      }
      
      // 确保专利排名数据存在
      if (!result.patentRanking || !Array.isArray(result.patentRanking)) {
        result.patentRanking = [];
      }
      
      return result;
    };
    
    // 修复区域数据格式
    const fixRegionData = (data) => {
      if (!data) return null;
      
      const result = { ...data };
      
      // 确保区域数据存在
      if (!result.regionData) {
        result.regionData = {};
      }
      
      return result;
    };

    const handleIndustryQuery = async (params) => {
      loading.value = true;
      try {
        console.log('发送行业查询参数:', params);
        
        // 确保参数不为null
        const industryId = params.industryId || '';
        const industryName = params.industryName || '';
        
        const response = await getCompanyStats({
          industryId,
          industryName,
          analysisType: 'industry'
        });
        
        console.log('行业分析API原始响应:', response);
        
        // 直接使用API返回的原始响应
        industryData.value = response;
        
        if (!industryData.value) {
          console.error('API返回数据为空');
          ElMessage.warning('获取行业数据失败，请重试');
          return;
        }
        
        // 输出详细的数据结构，帮助调试
        console.log('行业数据结构:', {
          type: typeof industryData.value,
          hasData: !!industryData.value,
          keys: industryData.value ? Object.keys(industryData.value) : [],
          isEmpty: !industryData.value || Object.keys(industryData.value).length === 0
        });
                
        // 确保图表容器已经渲染
        await nextTick();
        renderIndustryCharts();
        ElMessage.success(`${params.industryName}行业分析查询成功`);
      } catch (error) {
        console.error('行业分析查询失败:', error);
        ElMessage.error(`行业分析查询失败: ${error.message || '未知错误'}`);
      } finally {
        loading.value = false;
      }
    };

    const handleRegionQuery = async (params) => {
      loading.value = true;
      try {
        console.log('发送区域查询参数:', params);
        
        // 确保industryName不为null
        const industryName = params.industryName || '';
        
        // 使用industryName参数
        const response = await getCompanyStats({
          industryName,
          province: params.province || ''
        });
        
        console.log('区域分析API原始响应:', response);
        
        // 处理API响应数据
        if (Array.isArray(response)) {
          regionData.value = response;
        } else if (response && typeof response === 'object') {
          if (Array.isArray(response.data)) {
            regionData.value = response.data;
          } else if (Array.isArray(response.result)) {
            regionData.value = response.result;
          } else {
            // 如果返回的是对象格式，转换为数组格式
            const provinces = Object.keys(response).filter(key => 
              typeof response[key] === 'object' && response[key] !== null
            );
            
            if (provinces.length > 0) {
              regionData.value = provinces.map(province => ({
                province,
                ...response[province]
              }));
            } else {
              // 数据为空的情况
              console.warn('不能识别的数据格式，数据为空');
              regionData.value = [];
              ElMessage.warning('未获取到区域数据');
            }
          }
        } else {
          console.error('API返回格式不符合预期');
          ElMessage.warning('获取区域数据失败，返回格式异常');
          regionData.value = [];
        }
        
        // 确保数据中包含必要的字段
        if (!regionData.value || !regionData.value.length) {
          console.error('API返回区域数据为空');
          ElMessage.warning('未获取到区域数据');
          regionData.value = [];
        }
        
        // 处理数据，确保每个项目都有province字段
        regionData.value = regionData.value.map(item => {
          if (!item.province && (item.name || item.region || item.area || item.provinceName)) {
            return {
              ...item,
              province: item.name || item.region || item.area || item.provinceName
            };
          }
          return item;
        });
        
        // 输出详细的数据结构，帮助调试
        console.log('区域数据结构:', {
          type: typeof regionData.value,
          hasData: !!regionData.value,
          isArray: Array.isArray(regionData.value),
          length: regionData.value ? regionData.value.length : 0,
          sampleItem: regionData.value && regionData.value.length > 0 ? regionData.value[0] : null
        });
        
        // 确保图表容器已经渲染
        await nextTick();
        
        // 渲染四个维度的图表
        renderCompanyCountChart();
        renderEmployeeCountChart();
        renderRegisteredCapitalChart();
        renderHighTechCountChart();
        
        ElMessage.success(`${params.industryName || '全行业'}区域分析查询成功`);
      } catch (error) {
        console.error('区域分析查询失败:', error);
        ElMessage.error(`区域分析查询失败: ${error.message || '未知错误'}`);
        // 数据为空的处理
        regionData.value = [];
        ElMessage.warning('未获取到区域数据');
      } finally {
        loading.value = false;
      }
    };

    // 企业数量图表渲染
    const companyCountChart = ref(null);
    let companyCountChartInstance = null;
    
    const renderCompanyCountChart = () => {
      try {
        if (!companyCountChart.value) return;
        
        // 初始化图表实例
        if (companyCountChartInstance) {
          companyCountChartInstance.dispose();
        }
        companyCountChartInstance = safeInitChart(companyCountChart.value);
        if (!companyCountChartInstance) return;
        
        // 检查数据是否为空
        if (!regionData.value || regionData.value.length === 0) {
          companyCountChartInstance.setOption({
            title: {
              text: '暂无企业数量数据',
              left: 'center',
              top: 'center',
              textStyle: {
                color: '#909399',
                fontSize: 14
              }
            }
          });
          return;
        }
        
        // 准备数据
        const chartData = regionData.value.map(item => ({
          name: item.province,
          value: typeof item.companyCount === 'number' ? item.companyCount : 0
        }))
        .sort((a, b) => b.value - a.value)
        .slice(0, 30); // 最多显示30个省份
        
        // 设置图表选项
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: chartData.map(item => item.name),
            axisLabel: {
              interval: 0,
              rotate: 30,
              fontSize: 10
            }
          },
          yAxis: {
            type: 'value',
            name: '企业数量'
          },
          series: [
            {
              name: '企业数量',
              type: 'bar',
              data: chartData.map(item => item.value),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#83bff6' },
                  { offset: 0.5, color: '#188df0' },
                  { offset: 1, color: '#188df0' }
                ])
              }
            }
          ]
        };
        
        // 渲染图表
        companyCountChartInstance.setOption(option);
        
      } catch(error) {
        console.error('企业数量图表渲染失败:', error);
        // 显示错误状态
        if (companyCountChartInstance) {
          companyCountChartInstance.setOption({
            title: {
              text: '数据加载失败',
              left: 'center',
              top: 'center',
              textStyle: {
                color: '#f56c6c',
                fontSize: 14
              }
            }
          });
        }
      }
    };
    
    // 员工数量图表渲染
    const employeeCountChart = ref(null);
    let employeeCountChartInstance = null;
    
    const renderEmployeeCountChart = () => {
      try {
        if (!employeeCountChart.value) return;
        
        // 初始化图表实例
        if (employeeCountChartInstance) {
          employeeCountChartInstance.dispose();
        }
        employeeCountChartInstance = safeInitChart(employeeCountChart.value);
        if (!employeeCountChartInstance) return;
        
        // 检查数据是否为空
        if (!regionData.value || regionData.value.length === 0) {
          employeeCountChartInstance.setOption({
            title: {
              text: '暂无员工数量数据',
              left: 'center',
              top: 'center',
              textStyle: {
                color: '#909399',
                fontSize: 14
              }
            }
          });
          return;
        }
        
        // 准备数据
        const chartData = regionData.value.map(item => ({
          name: item.province,
          value: typeof item.employeeCount === 'number' ? item.employeeCount : 0
        }))
        .sort((a, b) => b.value - a.value)
        .slice(0, 30); // 最多显示30个省份
        
        // 设置图表选项
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: chartData.map(item => item.name),
            axisLabel: {
              interval: 0,
              rotate: 30,
              fontSize: 10
            }
          },
          yAxis: {
            type: 'value',
            name: '员工数量'
          },
          series: [
            {
              name: '员工数量',
              type: 'bar',
              data: chartData.map(item => item.value),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#67c23a' },
                  { offset: 0.5, color: '#95d475' },
                  { offset: 1, color: '#c2e7b0' }
                ])
              }
            }
          ]
        };
        
        // 渲染图表
        employeeCountChartInstance.setOption(option);
        
      } catch(error) {
        console.error('员工数量图表渲染失败:', error);
        // 显示错误状态
        if (employeeCountChartInstance) {
          employeeCountChartInstance.setOption({
            title: {
              text: '数据加载失败',
              left: 'center',
              top: 'center',
              textStyle: {
                color: '#f56c6c',
                fontSize: 14
              }
            }
          });
        }
      }
    };
    
    // 注册资本图表渲染
    const registeredCapitalChart = ref(null);
    let registeredCapitalChartInstance = null;
    
    const renderRegisteredCapitalChart = () => {
      try {
        if (!registeredCapitalChart.value) return;
        
        // 初始化图表实例
        if (registeredCapitalChartInstance) {
          registeredCapitalChartInstance.dispose();
        }
        registeredCapitalChartInstance = safeInitChart(registeredCapitalChart.value);
        if (!registeredCapitalChartInstance) return;
        
        // 检查数据是否为空
        if (!regionData.value || regionData.value.length === 0) {
          registeredCapitalChartInstance.setOption({
            title: {
              text: '暂无注册资本数据',
              left: 'center',
              top: 'center',
              textStyle: {
                color: '#909399',
                fontSize: 14
              }
            }
          });
          return;
        }
        
        // 准备数据
        const chartData = regionData.value.map(item => ({
          name: item.province,
          value: typeof item.registeredCapital === 'number' ? item.registeredCapital : 0
        }))
        .sort((a, b) => b.value - a.value)
        .slice(0, 30); // 最多显示30个省份
        
        // 设置图表选项 - 饼图展示
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 20,
            bottom: 20,
            data: chartData.map(item => item.name)
          },
          series: [
            {
              name: '注册资本',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 4,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 12,
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: chartData
            }
          ]
        };
        
        // 渲染图表
        registeredCapitalChartInstance.setOption(option);
        
      } catch(error) {
        console.error('注册资本图表渲染失败:', error);
        // 显示错误状态
        if (registeredCapitalChartInstance) {
          registeredCapitalChartInstance.setOption({
            title: {
              text: '数据加载失败',
              left: 'center',
              top: 'center',
              textStyle: {
                color: '#f56c6c',
                fontSize: 14
              }
            }
          });
        }
      }
    };
    
    // 高新企业数量图表渲染
    const highTechCountChart = ref(null);
    let highTechCountChartInstance = null;
    
    const renderHighTechCountChart = () => {
      try {
        if (!highTechCountChart.value) return;
        
        // 初始化图表实例
        if (highTechCountChartInstance) {
          highTechCountChartInstance.dispose();
        }
        highTechCountChartInstance = safeInitChart(highTechCountChart.value);
        if (!highTechCountChartInstance) return;
        
        // 检查数据是否为空
        if (!regionData.value || regionData.value.length === 0) {
          highTechCountChartInstance.setOption({
            title: {
              text: '暂无高新企业数据',
              left: 'center',
              top: 'center',
              textStyle: {
                color: '#909399',
                fontSize: 14
              }
            }
          });
          return;
        }
        
        // 准备数据
        const chartData = regionData.value.map(item => ({
          name: item.province,
          value: typeof item.highTechCount === 'number' ? item.highTechCount : 0
        }))
        .sort((a, b) => b.value - a.value)
        .slice(0, 30); // 最多显示30个省份
        
        // 设置图表选项 - 折线图展示
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: chartData.map(item => item.name),
            axisLabel: {
              interval: 'auto',
              rotate: 30,
              fontSize: 10
            }
          },
          yAxis: {
            type: 'value',
            name: '高新企业数量'
          },
          series: [
            {
              name: '高新企业数量',
              type: 'line',
              stack: 'Total',
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              data: chartData.map(item => item.value),
              smooth: true,
              lineStyle: {
                width: 3,
                color: '#f56c6c'
              },
              itemStyle: {
                color: '#f56c6c'
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(245, 108, 108, 0.5)' },
                  { offset: 1, color: 'rgba(245, 108, 108, 0.1)' }
                ])
              }
            }
          ]
        };
        
        // 渲染图表
        highTechCountChartInstance.setOption(option);
        
      } catch(error) {
        console.error('高新企业数量图表渲染失败:', error);
        // 显示错误状态
        if (highTechCountChartInstance) {
          highTechCountChartInstance.setOption({
            title: {
              text: '数据加载失败',
              left: 'center',
              top: 'center',
              textStyle: {
                color: '#f56c6c',
                fontSize: 14
              }
            }
          });
        }
      }
    };

    // 渲染行业分析图表
    const renderIndustryCharts = () => {
      if (!industryData.value) return;
      
      try {
        // 初始化图表实例
        initChartInstances();
        
        // 渲染各类图表
        renderCompanySizeChart();
        renderCompanyTypeChart();
        renderPatentRankChart();
        renderInnovationEfficiencyChart();
      } catch(error) {
        console.error('图表渲染总体失败:', error);
      }
    };

    // 初始化图表实例
    const initChartInstances = () => {
      try {
        // 初始化企业规模分布图表
        if (companySizeChart.value) {
          if (companySizeChartInstance) {
            companySizeChartInstance.dispose();
          }
          companySizeChartInstance = safeInitChart(companySizeChart.value);
        }
      } catch(error) {
        console.error('企业规模图表初始化失败:', error);
      }
      
      try {
        // 初始化企业类型分布图表
        if (companyTypeChart.value) {
          if (companyTypeChartInstance) {
            companyTypeChartInstance.dispose();
          }
          companyTypeChartInstance = safeInitChart(companyTypeChart.value);
        }
      } catch(error) {
        console.error('企业类型图表初始化失败:', error);
      }
      
      try {
        // 初始化专利排名图表
        if (patentRankChart.value) {
          if (patentRankChartInstance) {
            patentRankChartInstance.dispose();
          }
          patentRankChartInstance = safeInitChart(patentRankChart.value);
        }
      } catch(error) {
        console.error('专利排名图表初始化失败:', error);
      }
      
      try {
        // 初始化创新效率图表
        if (innovationChart.value) {
          if (innovationChartInstance) {
            innovationChartInstance.dispose();
          }
          innovationChartInstance = safeInitChart(innovationChart.value);
        }
      } catch(error) {
        console.error('创新效率图表初始化失败:', error);
      }
      
      try {
        // 初始化区域排名图表
        if (regionRankChart.value) {
          if (regionRankChartInstance) {
            regionRankChartInstance.dispose();
          }
          regionRankChartInstance = safeInitChart(regionRankChart.value);
        }
      } catch(error) {
        console.error('区域排名图表初始化失败:', error);
      }
    };

    // 渲染企业规模分布图
    const renderCompanySizeChart = () => {
      try {
        if (!companySizeChartInstance || !industryData.value) return;
        
        // 获取原始数据
        const data = industryData.value;
        console.log('企业规模分布原始数据:', data);
        
        // 优先使用companySizeDistribution字段
        let sizeDistribution = null;
        if (Array.isArray(data.companySizeDistribution)) {
          sizeDistribution = data.companySizeDistribution;
          console.log('使用数组格式的companySizeDistribution');
        } else if (data.companySizeDistribution && typeof data.companySizeDistribution === 'object') {
          sizeDistribution = data.companySizeDistribution;
          console.log('使用对象格式的companySizeDistribution');
        } else {
          // 尝试从其他可能的位置查找数据
          const possibleKeys = ['sizeDistribution', 'companyScales', 'scales', 'sizeData'];
          for (const key of possibleKeys) {
            if (data[key]) {
              sizeDistribution = data[key];
              console.log(`找到企业规模分布数据，位于字段:${key}`);
              break;
            }
          }
        }
        
        // 如果找不到数据，使用默认值
        if (!sizeDistribution) {
          console.warn('无法找到企业规模分布数据，使用默认数据');
          sizeDistribution = [
            { size: '大型企业', count: 10 },
            { size: '中型企业', count: 20 },
            { size: '小型企业', count: 40 },
            { size: '微型企业', count: 30 }
          ];
        }
        
        // 将数据转换为图表所需格式
        let chartData = [];
        
        // 处理数组格式
        if (Array.isArray(sizeDistribution)) {
          chartData = sizeDistribution.map(item => {
            // 获取名称
            const name = item.name || item.size || '未知规模';
            // 获取数值
            let value = 0;
            if (typeof item.value === 'number') {
              value = item.value;
            } else if (typeof item.count === 'number') {
              value = item.count;
            } else {
              // 尝试找其他可能的字段
              const possibleValueKeys = Object.keys(item).filter(k => 
                typeof item[k] === 'number' && 
                (k.toLowerCase().includes('count') || k.toLowerCase().includes('value') || k.toLowerCase().includes('num'))
              );
              
              if (possibleValueKeys.length > 0) {
                value = item[possibleValueKeys[0]];
              } else {
                value = 1; // 默认值
              }
            }
            
            return { name, value };
          });
        } 
        // 处理对象格式
        else if (typeof sizeDistribution === 'object') {
          chartData = Object.entries(sizeDistribution).map(([key, value]) => {
            return {
              name: key,
              value: typeof value === 'number' ? value : 
                    typeof value === 'object' && value !== null && typeof value.count === 'number' ? value.count :
                    typeof value === 'object' && value !== null && typeof value.value === 'number' ? value.value : 1
            };
          });
        }
        
        // 确保有数据显示
        if (chartData.length === 0) {
          chartData = [
            { name: '大型企业', value: 10 },
            { name: '中型企业', value: 20 },
            { name: '小型企业', value: 40 },
            { name: '微型企业', value: 30 }
          ];
        }
        
        console.log('处理后的企业规模图表数据:', chartData);
        
        // 设置图表选项
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: chartData.map(item => item.name)
          },
          series: [
            {
              name: '企业规模',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 4,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '16',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: chartData
            }
          ]
        };
        
        companySizeChartInstance.setOption(option);
      } catch(error) {
        console.error('企业规模分布图渲染失败:', error);
        companySizeChartInstance?.setOption({
          title: {
            text: '数据解析错误',
            left: 'center',
            top: 'center'
          }
        });
      }
    };

    // 渲染企业类型分布图
    const renderCompanyTypeChart = () => {
      try {
        if (!companyTypeChartInstance || !industryData.value) return;
        
        // 由于API没有直接返回企业类型分布数据，我们需要创建一个默认的分布
        // 可以根据industryStatistics中的数据创建比例
        const data = industryData.value;
        console.log('企业类型分布原始数据:', data);
        
        // 由于API没有提供企业类型分布数据，我们使用默认示例数据
        // 这里可以根据实际需求修改
        let typeDistribution = null;
        
        // 使用默认类型分布数据
        console.warn('无法找到企业类型分布数据，使用默认数据');
        typeDistribution = [
          { type: '有限责任公司', count: 50 },
          { type: '股份有限公司', count: 20 },
          { type: '个体工商户', count: 15 },
          { type: '其他类型', count: 15 }
        ];
        
        console.log('使用的企业类型分布数据:', typeDistribution);
        
        // 将数据转换为图表所需格式
        let chartData = [];
        
        // 处理数组格式
        if (Array.isArray(typeDistribution)) {
          chartData = typeDistribution.map(item => {
            // 获取名称
            const name = item.name || item.type || '未知类型';
            // 获取数值
            let value = 0;
            if (typeof item.value === 'number') {
              value = item.value;
            } else if (typeof item.count === 'number') {
              value = item.count;
            } else {
              // 尝试找其他可能的字段
              const possibleValueKeys = Object.keys(item).filter(k => 
                typeof item[k] === 'number' && 
                (k.toLowerCase().includes('count') || k.toLowerCase().includes('value') || k.toLowerCase().includes('num'))
              );
              
              if (possibleValueKeys.length > 0) {
                value = item[possibleValueKeys[0]];
              } else {
                value = 1; // 默认值
              }
            }
            
            return { name, value };
          });
        } 
        // 处理对象格式
        else if (typeof typeDistribution === 'object') {
          chartData = Object.entries(typeDistribution).map(([key, value]) => {
            return {
              name: key,
              value: typeof value === 'number' ? value : 
                    typeof value === 'object' && value !== null && typeof value.count === 'number' ? value.count :
                    typeof value === 'object' && value !== null && typeof value.value === 'number' ? value.value : 1
            };
          });
        }
        
        // 确保有数据显示
        if (chartData.length === 0) {
          chartData = [
            { name: '有限责任公司', value: 50 },
            { name: '股份有限公司', value: 20 },
            { name: '个体工商户', value: 15 },
            { name: '其他类型', value: 15 }
          ];
        }
        
        console.log('处理后的企业类型图表数据:', chartData);
        
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: chartData.map(item => item.name)
          },
          series: [
            {
              name: '企业类型',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 4,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '16',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: chartData
            }
          ]
        };
        
        companyTypeChartInstance.setOption(option);
      } catch(error) {
        console.error('企业类型分布图渲染失败:', error);
        companyTypeChartInstance?.setOption({
          title: {
            text: '数据解析错误',
            left: 'center',
            top: 'center'
          }
        });
      }
    };

    // 渲染专利排名图
    const renderPatentRankChart = () => {
      try {
        if (!patentRankChartInstance || !industryData.value) return;
        
        const data = industryData.value;
        console.log('专利排名原始数据:', data);
        
        // 优先使用patentDistribution字段
        let patentRanking = null;
        if (Array.isArray(data.patentDistribution)) {
          patentRanking = data.patentDistribution;
          console.log('使用patentDistribution字段');
        } else if (Array.isArray(data.patentRanking)) {
          patentRanking = data.patentRanking;
          console.log('使用patentRanking字段');
        } else {
          // 尝试从其他可能的字段查找数据
          const possibleKeys = ['patentRank', 'patentTop', 'patentTop10', 'patents'];
          for (const key of possibleKeys) {
            if (Array.isArray(data[key])) {
              patentRanking = data[key];
              console.log(`找到专利排名数据，位于字段:${key}`);
              break;
            }
          }
        }
        
        // 如果未找到数据，使用默认数据
        if (!patentRanking || !Array.isArray(patentRanking) || patentRanking.length === 0) {
          console.warn('未找到专利排名数据，使用默认数据');
          patentRanking = [
            { company: '示例企业1', patents: 100 },
            { company: '示例企业2', patents: 80 },
            { company: '示例企业3', patents: 60 },
            { company: '示例企业4', patents: 50 },
            { company: '示例企业5', patents: 40 }
          ];
        }
        
        // 规范化数据格式
        const normalizedData = patentRanking.map(item => {
          // 获取公司名称
          let companyName = '未知企业';
          if (typeof item.company === 'string') {
            companyName = item.company;
          } else if (typeof item.companyName === 'string') {
            companyName = item.companyName;
          } else if (typeof item.name === 'string') {
            companyName = item.name;
          }
          
          // 获取专利数量
          let patentCount = 0;
          if (typeof item.patents === 'number') {
            patentCount = item.patents;
          } else if (typeof item.patentCount === 'number') {
            patentCount = item.patentCount;
          } else if (typeof item.count === 'number') {
            patentCount = item.count;
          } else if (typeof item.value === 'number') {
            patentCount = item.value;
          }
          
          return {
            companyName: companyName.toString().substring(0, 20), // 截断过长名称
            patentCount
          };
        });
        
        // 排序并获取前10名
        const top10 = normalizedData
          .filter(item => item.companyName && item.patentCount)
          .sort((a, b) => b.patentCount - a.patentCount)
          .slice(0, 10);
        
        console.log('处理后的专利Top10数据:', top10);
        
        // 设置图表选项
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            name: '专利数量'
          },
          yAxis: {
            type: 'category',
            data: top10.map(item => item.companyName),
            axisLabel: {
              width: 120,
              overflow: 'truncate'
            }
          },
          series: [
            {
              name: '专利数量',
              type: 'bar',
              data: top10.map(item => item.patentCount)
            }
          ]
        };
        
        patentRankChartInstance.setOption(option);
      } catch(error) {
        console.error('专利排名图渲染失败:', error);
        patentRankChartInstance?.setOption({
          title: {
            text: '数据解析错误',
            left: 'center',
            top: 'center'
          }
        });
      }
    };

    // 渲染创新效率排行图表
    const renderInnovationEfficiencyChart = () => {
      if (!innovationChartInstance || !industryData.value) return;
      
      console.log('创新效率数据:', industryData.value);
      const data = industryData.value;
      
      try {
        // 检查是否有创新效率数据
        if (!data.innovationEfficiency || !Array.isArray(data.innovationEfficiency) || data.innovationEfficiency.length === 0) {
          console.warn('未找到创新效率数据，显示空状态');
          innovationChartInstance.setOption({
            title: { text: '暂无创新效率数据', left: 'center', top: 'middle' }
          });
          return;
        }
        
        // 规范化数据格式
        const normalizedData = data.innovationEfficiency.map(item => {
          // 获取公司名称
          let companyName = '未知企业';
          if (typeof item.company === 'string') {
            companyName = item.company;
          } else if (typeof item.companyName === 'string') {
            companyName = item.companyName;
          } else if (typeof item.name === 'string') {
            companyName = item.name;
          }
          
          // 获取创新效率值
          let efficiency = 0;
          if (typeof item.efficiency === 'number') {
            efficiency = item.efficiency;
          } else if (typeof item.value === 'number') {
            efficiency = item.value;
          } else if (typeof item.ratio === 'number') {
            efficiency = item.ratio;
          }
          
          return {
            companyName: companyName.toString().substring(0, 20), // 截断过长名称
            efficiency
          };
        });
        
        // 按照创新效率排序并取前10
        const top10 = normalizedData
          .filter(item => item.companyName && item.efficiency)
          .sort((a, b) => b.efficiency - a.efficiency)
          .slice(0, 10);
        
        console.log('处理后的创新效率Top10数据:', top10);
        
        if (top10.length === 0) {
          innovationChartInstance.setOption({
            title: { text: '暂无创新效率数据', left: 'center', top: 'middle' }
          });
          return;
        }
        
        // 设置图表选项
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              const data = params[0];
              return `${data.name}: ${data.value.toFixed(2)}`;
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: top10.map(item => item.companyName),
            axisLabel: {
              interval: 0,
              rotate: 30,
              textStyle: {
                fontSize: 12
              }
            }
          },
          yAxis: {
            type: 'value',
            name: '创新效率'
          },
          series: [
            {
              name: '创新效率',
              type: 'bar',
              data: top10.map(item => item.efficiency),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#83bff6' },
                  { offset: 0.5, color: '#188df0' },
                  { offset: 1, color: '#188df0' }
                ])
              }
            }
          ]
        };
        
        innovationChartInstance.setOption(option);
      } catch (error) {
        console.error('渲染创新效率图表失败:', error);
        innovationChartInstance?.setOption({
          title: {
            text: '数据解析错误',
            left: 'center',
            top: 'center'
          }
        });
      }
    };

    // 渲染区域地图图表
    const renderRegionMapChart = () => {
      if (!regionData.value) return;
      
      console.log('准备渲染区域地图，数据:', regionData.value);
      
      try {
        // 确保地图组件使用的是数组格式数据
        if (!Array.isArray(regionData.value)) {
          console.warn('区域数据不是数组格式，无法渲染地图');
          return;
        }
        
        // 检查数据中是否包含省份信息
        const hasProvinceInfo = regionData.value.some(item => item && item.province);
        if (!hasProvinceInfo) {
          console.warn('区域数据中缺少省份信息，无法渲染地图');
          
          // 尝试重构数据格式，确保每个项目都有province字段
          regionData.value = regionData.value.map(item => {
            if (item && !item.province) {
              // 如果item有name字段但没有province字段，可能是省份名在name字段
              if (item.name) {
                return { ...item, province: item.name };
              }
              
              // 查找可能包含省份名的字段
              const possibleProvinceFields = ['region', 'provinceName', 'regionName', 'area'];
              for (const field of possibleProvinceFields) {
                if (item[field]) {
                  return { ...item, province: item[field] };
                }
              }
            }
            return item;
          });
        }
        
        // 通过RegionMapChart组件，数据将被自动处理
        // 只需确保传入的是正确的数组格式
        console.log('区域地图渲染完成');
      } catch (error) {
        console.error('区域地图渲染失败:', error);
      }
    };

    // 格式化数值显示
    const formatValue = (value) => {
      if (value === undefined || value === null) {
        return '暂无数据';
      }
      
      if (typeof value !== 'number') {
        return value.toString();
      }
      
      // 处理数字格式化
      if (value >= 100000000) {
        return (value / 100000000).toFixed(2) + '亿';
      } else if (value >= 10000) {
        return (value / 10000).toFixed(2) + '万';
      } else if (value >= 1000) {
        return (value / 1000).toFixed(2) + '千';
      } else {
        return value.toString();
      }
    };

    // 处理维度变化
    const handleDimensionChange = (dimension) => {
      activeDimension.value = dimension;
      console.log('切换维度为:', dimension);
      // 如果有区域数据，重新渲染相关图表
      if (regionData.value && regionData.value.length > 0) {
        nextTick(() => {
          renderCompanyCountChart();
          renderEmployeeCountChart();
          renderRegisteredCapitalChart();
          renderHighTechCountChart();
        });
      }
    };

    // 窗口大小变化处理函数
    const handleResize = () => {
      // 调整单独维护的图表实例
      companySizeChartInstance?.resize();
      companyTypeChartInstance?.resize();
      patentRankChartInstance?.resize();
      regionRankChartInstance?.resize();
      companyCountChartInstance?.resize();
      employeeCountChartInstance?.resize();
      registeredCapitalChartInstance?.resize();
      highTechCountChartInstance?.resize();
      innovationChartInstance?.resize();
      
      // 同时调整所有在chartInstances中收集的图表实例
      chartInstances.forEach(chart => {
        if (chart && typeof chart.resize === 'function') {
          try {
            chart.resize();
          } catch (error) {
            console.error('图表调整大小失败:', error);
          }
        }
      });
    };
    
    // 防抖处理的resize函数
    const debouncedResize = debounce(handleResize, 200);

    // 生命周期钩子
    onMounted(async () => {
      // 先检测API环境
      await checkApiEnvironment();
      // 初始化图表实例
      initChartInstances();
      // 处理URL查询参数
      processQueryParams();
      
      // 添加窗口大小变化监听
      window.addEventListener('resize', debouncedResize);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', debouncedResize);
      
      // 销毁图表实例
      companySizeChartInstance?.dispose();
      companyTypeChartInstance?.dispose();
      patentRankChartInstance?.dispose();
      regionRankChartInstance?.dispose();
      innovationChartInstance?.dispose();
      companyCountChartInstance?.dispose();
      employeeCountChartInstance?.dispose();
      registeredCapitalChartInstance?.dispose();
      highTechCountChartInstance?.dispose();
    });

    // 创建模拟区域数据
    const createMockRegionData = () => {
      return [
        { province: '北京', companyCount: 911, employeeCount: 91100, registeredCapital: 9110, highTechCount: 456 },
        { province: '上海', companyCount: 820, employeeCount: 82000, registeredCapital: 8200, highTechCount: 410 },
        { province: '广东', companyCount: 750, employeeCount: 75000, registeredCapital: 7500, highTechCount: 375 },
        { province: '江苏', companyCount: 680, employeeCount: 68000, registeredCapital: 6800, highTechCount: 340 },
        { province: '浙江', companyCount: 610, employeeCount: 61000, registeredCapital: 6100, highTechCount: 305 },
        { province: '山东', companyCount: 540, employeeCount: 54000, registeredCapital: 5400, highTechCount: 270 },
        { province: '安徽', companyCount: 470, employeeCount: 47000, registeredCapital: 4700, highTechCount: 235 },
        { province: '河南', companyCount: 400, employeeCount: 40000, registeredCapital: 4000, highTechCount: 200 },
        { province: '湖北', companyCount: 330, employeeCount: 33000, registeredCapital: 3300, highTechCount: 165 },
        { province: '四川', companyCount: 260, employeeCount: 26000, registeredCapital: 2600, highTechCount: 130 },
        { province: '重庆', companyCount: 190, employeeCount: 19000, registeredCapital: 1900, highTechCount: 95 },
        { province: '福建', companyCount: 120, employeeCount: 12000, registeredCapital: 1200, highTechCount: 60 }
      ];
    };

    return {
      activeTab,
      loading,
      industryData,
      regionData,
      industryStats,
      activeDimension,
      getDimensionTitle,
      emptyDescription,
      companySizeChart,
      companyTypeChart,
      patentRankChart,
      regionRankChart,
      innovationChart,
      handleTabClick,
      handleIndustryQuery,
      handleRegionQuery,
      handleDimensionChange,
      formatValue,
      backToMain,
      isFromMainPage,
      dataReady,
      companyCountChart,
      employeeCountChart,
      registeredCapitalChart,
      highTechCountChart
    };
  }
};
</script>

<style scoped>
.industry-analysis-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 120px);
  overflow-x: hidden; /* 防止横向溢出 */
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--el-border-color-light);
  flex-wrap: wrap; /* 小屏幕时自动换行 */
  gap: 10px; /* 元素之间的间距 */
}

.api-status-alert {
  margin-bottom: 15px;
}

.empty-tip {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.analysis-tabs {
  margin-bottom: 20px;
}

/* 改进标签页样式，与主页面风格一致 */
.industry-analysis-container :deep(.el-tabs) {
  margin-bottom: 25px;
}

.industry-analysis-container :deep(.el-tabs__header) {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  border-bottom: none;
}

.industry-analysis-container :deep(.el-tabs__nav-wrap) {
  display: flex;
  justify-content: center;
  overflow: hidden; /* 防止溢出 */
}

.industry-analysis-container :deep(.el-tabs__nav) {
  background-color: var(--el-color-primary-light-9);
  border-radius: 24px;
  box-shadow: 0 8px 24px rgba(50, 50, 93, 0.1), 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 8px;
  border: none;
  position: relative;
  z-index: 1;
  max-width: 100%; /* 限制最大宽度 */
  overflow: hidden; /* 防止溢出 */
}

.industry-analysis-container :deep(.el-tabs__item) {
  height: 48px;
  line-height: 48px;
  min-width: 100px; /* 减小最小宽度以适应小屏幕 */
  font-size: 14px;
  color: var(--el-text-color-regular);
  border-radius: 20px;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  padding: 0 15px; /* 减小内边距 */
  margin: 0 4px; /* 减小外边距 */
  border: none;
  background-color: rgba(255, 255, 255, 0.5);
  white-space: nowrap; /* 防止标签文字换行 */
  overflow: hidden;
  text-overflow: ellipsis;
}

.industry-analysis-container :deep(.el-tabs__item.is-active) {
  color: var(--el-color-white);
  background-color: var(--el-color-primary);
  font-weight: 600;
  box-shadow: 0 4px 12px var(--el-color-primary-light-5);
}

.industry-analysis-container :deep(.el-tabs__item:hover:not(.is-active)) {
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-8);
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 5px;
}

.analysis-layout {
  display: flex;
  gap: 20px;
  flex: 1;
  overflow: hidden;
}

.form-card {
  width: 300px;
  flex-shrink: 0;
  height: fit-content;
  max-width: 100%; /* 确保不超出容器 */
}

.result-card {
  flex: 1;
  min-height: 500px;
  overflow: auto;
}

/* 响应式布局增强 */
@media (max-width: 1200px) {
  .analysis-layout {
    flex-direction: column;
  }

  .form-card {
    width: 100%;
    max-width: 100%;
  }
}

/* 添加更小屏幕的响应式布局 */
@media (max-width: 768px) {
  .industry-analysis-container {
    padding: 10px;
  }
  
  .stat-cards .el-col {
    width: 100% !important; /* 强制统计卡片在小屏幕上一行显示一个 */
    margin-bottom: 10px;
  }
  
  .chart-row .el-col {
    width: 100% !important; /* 强制图表在小屏幕上一行显示一个 */
    margin-bottom: 15px;
  }
  
  /* 调整四象限布局 */
  .quadrant-layout {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  
  .quadrant-card {
    width: 100% !important;
  }
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  height: 100px;
  overflow: hidden;
  margin-bottom: 10px; /* 添加底部边距 */
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  margin-right: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border-radius: 8px;
  background: rgba(64, 158, 255, 0.1);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  line-height: 1.2;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

/* 修复图表容器样式 */
.chart-container {
  height: 300px;
  width: 100%;
  overflow: hidden;
}

/* 区域统计图表样式优化 */
.region-stats {
  width: 100%;
}

.region-stats-title {
  margin-bottom: 20px;
  text-align: center;
}

.region-stats-desc, .region-stats-hint {
  font-size: 14px;
  color: #606266;
  margin: 8px 0;
}

/* 优化四象限布局 */
.quadrant-layout {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.quadrant-card {
  margin-bottom: 0; /* 移除底部边距，由grid gap控制 */
}

.chart-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 确保所有图表边距一致 */
.chart-card {
  margin-bottom: 20px;
}

.chart-card:last-child {
  margin-bottom: 0;
}
</style> 